<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function fn(k, n) {
      let res = []
      function helper(sum, target, paths, start) {
        if (sum === target) {
          // 结果数字个数等于 k 个，入选结果
          if (paths.length === k) res.push(paths)
          return
        }
        // 选择范围 9 个数
        for (let i = start; i <= 9; i++) {
          // 结果数字个数大于 k 个跳过
          if (paths.length > k) break

          // 剪枝
          if (target - sum >= i) {
            helper(sum + i, target, [...paths, i], i + 1) // i+1 去重
          }
        }
      }
      helper(0, n, [], 1)
      return res
    }
    console.log(fn(3, 9))
  </script>
</body>

</html>